<template>
  <div>
    <n-card :bordered="false" class="proCard" :style="{ height: `${bodyHeight}px` }">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.roleId"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <Edit ref="editRef" @reloadTable="reloadTable"></Edit>
    <RoleMenu ref="roleMenuRef"></RoleMenu>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, h, onMounted } from 'vue';
import { useMessage, useDialog, NSwitch, NTag } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { getPageList, deleteById, updateEnabled } from '@/api/system/role';
import { getMenuList } from '@/api/system/menu';
import { PlusOutlined } from '@vicons/antd';
import { getTreeAll } from '@/utils';
import { useRouter } from 'vue-router';

import Edit from './edit.vue';
import RoleMenu from './roleMenu.vue';

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const actionRef = ref();
const dialog = useDialog();

const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref('');
const expandedKeys = ref([]);
const checkedKeys = ref(['console', 'step-form']);
const editRef = ref(null);
const roleMenuRef = ref(null);

const columns = [
  {
    title: '#',
    key: 'key',
    width: 20,
    render: (_, index) => {
      return `${index + 1}`;
    },
  },
  {
    title: '角色编号',
    key: 'roleCode',
    width: 100,
  },
  {
    title: '角色名称',
    key: 'roleName',
    width: 100,
  },
  {
    title: '是否启用',
    key: 'enabled',
    width: 100,
    render(row, index) {
      return h(NSwitch, {
        value: row.enabled,
        onUpdateValue(v) {
          updateEnabled({
            roleId: row.roleId,
            enabled: v,
          }).then((res) => {
            if (res.success) {
              message.success('修改状态成功');
              reloadTable();
            }
          });
        },
      });
    },
  },
];

const formParams = reactive({
  roleCode: '',
  roleName: '',
});

const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '菜单权限',
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          //auth: ['basic_list'],
        },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          //auth: ['basic_list'],
        },
        {
          label: '删除',
          icon: 'ic:outline-delete-outline',
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          //auth: ['basic_list'],
        },
      ],
    });
  },
});

function addTable() {
  editRef.value.open();
}

const loadDataTable = async (res: any) => {
  var data = await getPageList({ ...formParams, ...res });
  return data.result;
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      message.success('新建成功');
      setTimeout(() => {
        showModal.value = false;
        reloadTable();
      });
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

function handleEdit(record: Recordable) {
  editRef.value.open(record);
}

function handleDelete(record: Recordable) {
  dialog.info({
    title: '提示',
    content: `您确定想删除吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      deleteById(record.roleId).then((res) => {
        if (res.success) {
          message.success('删除成功');
          reloadTable();
        }
      });
    },
    onNegativeClick: () => {
      message.error('已取消');
    },
  });
}

function handleMenuAuth(record: Recordable) {
  // editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
  // checkedKeys.value = record.menu_keys;
  roleMenuRef.value.open(record);
}

function checkedTree(keys) {
  checkedKeys.value = [checkedKeys.value, ...keys];
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = treeData.value.map((item: any) => item.key) as [];
  }
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = getTreeAll(treeData.value);
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

onMounted(async () => {
  // const treeMenuList = await getMenuList();
  // expandedKeys.value = treeMenuList.list.map((item) => item.key);
  // treeData.value = treeMenuList.list;
});
</script>

<style lang="less" scoped></style>
